#coding=utf-8
# Copyright 2011-2013 Maxim Petrov <maximpetrov@yahoo.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 3 or any later version.

from revision_panel import RevisionPanel
from ok_cancel_window import OKCancelWindow
from message_window import ErrorWindow
import curses
import os

class LocalRevisionPanel(RevisionPanel):
    """
    This class used for draw panel that show table of revisions
    of selected files.
    """
    
    __filelist = []
    workdir_panel = None
    def __init__(self, main_window):
        """
        Constructor of local revision panel

        @param:
            main_window -- instance of MainWindow
       """
        self._panel_header = _(u'Revision')
        RevisionPanel.__init__(self, main_window)
        self.hotkeys.update({7: _(u'Revert')})
        self.show_all_revs = False

    def view(self, files):
        """
        This function receives the current selected files as array[]
        and refreshes the revision panel.
        """

        self.__filelist = []
        self.__filelist.extend(files)
        self._update_content()

    def _no_revisions_string(self):
        """
        function for get string reports that there are no revisions to show
        """

        return self.__filelist and ngettext(u'No revision for file: [{0}]',
                         u'No revision for files: [{0}]', len(self.__filelist)).\
                                            format(u', '.join(self.__filelist))\
                or _(u'No files selected')

    def _get_table_content(self):
        """
        Function to get content to show in table
        """
        if self.show_all_revs:
            log = self._main_window.repo_util.get_full_log()
            log.reverse()
        else:
            log = self._main_window.repo_util.get_log(self.__filelist)
            log.reverse()
            
        #log = self._main_window.repo_util.get_full_log()
        return log

    def handle_keypress(self, ch, uni):
        """
        Handle keypress.

        @param:
            ch -- pressed key
            uni - True if ch is Unicode symbol, False otherwise
        """
        if ch == curses.KEY_F7:
            files = self.__filelist
            rev = self.get_selected_revision_number()
            if rev is None:
                msg = ErrorWindow(_(u'No revision selected'))
                self._main_window.show_modal_window(msg)
            else:
                msg = OKCancelWindow(_(u"You are going to revert selected files "
                                       u"to rev. {0}").format(rev), _(u'Revert'))
                if self._main_window.show_modal_window(msg)[u'button'] == u"OK":
                    if not self._main_window.repo_util.revert(files, rev):
                        msg = ErrorWindow(self._main_window.repo_util.local_error)
                        self._main_window.show_modal_window(msg)
                        # Сброс ошибки после отображения
                        self._main_window.repo_util.local_error = None
        elif ch == curses.ascii.ctrl(ord('U')): #Ctrl-U
            rev = self.get_selected_revision_number()
            if rev is None:
                msg = ErrorWindow(_(u'No revision selected'))
                self._main_window.show_modal_window(msg)
            else:
                msg = OKCancelWindow(_(u"You are going to update repo "
                                       u"to rev. {0}").format(rev), _(u'Update'))
                if self._main_window.show_modal_window(msg)[u'button'] == u"OK":
                    self._main_window.hide()
                    if not self._main_window.repo_util.update(rev):
                        self._main_window.unhide()
                        msg = ErrorWindow(self._main_window.repo_util.local_error)
                        self._main_window.show_modal_window(msg)
                        # Сброс ошибки после отображения
                        self._main_window.repo_util.local_error = None
                    else:
                        self._main_window.unhide()
                self._update_content()
                self.set_active()
            #a = self._main_window.repo_util.get_full_log()
        # changes in selected revision (only if one file selected) or between selected and marked revision (if some revision marked)
        elif ch == curses.KEY_F12:
            if len(self.__filelist) == 1:
                if self._diff_sel_rev == -1:
                    try:
                        files = self._main_window.repo_util.diff(self.__filelist[0],
                                            rev1=self.get_selected_revision_number(),
                                            changes=True)
                    except Exception:
                        pass
                    else:
                        self._main_window.show_diff_panel(files,
                            title=(self.__filelist[0] + u':' + unicode(self._main_window.repo_util.get_parent(
                                            self.get_selected_revision_number(), filename=self.__filelist[0])),
                                   self.__filelist[0] + u':' + unicode(self.get_selected_revision_number())))
                else:
                    try:
                        files = self._main_window.repo_util.diff(self.__filelist[0],
                                            rev1=self.get_selected_revision_number(),
                                            rev2=self.get_diff_selected_revision_number())
                    except Exception:
                        pass
                    else:
                        self._main_window.show_diff_panel(files,
                            title=(self.__filelist[0] + u':' + unicode(self.get_diff_selected_revision_number()),
                                   self.__filelist[0] + u':' + unicode(self.get_selected_revision_number())))
        # changes in selected revision (only if one file selected) to workcopy
        elif ch == int(self._main_window.settings.get(u'Keycodes', u'KEY_SHIFT_F12', False) or -1):
            if len(self.__filelist) == 1:
                try:
                    files = self._main_window.repo_util.diff(self.__filelist[0],
                        rev1=self.get_selected_revision_number())
                except Exception:
                    pass
                else:
                    self._main_window.show_diff_panel(files,
                        title=(self.__filelist[0] + u':' + unicode(self.get_selected_revision_number()),
                               self.__filelist[0]))
        # view content for selected revision (only if one file selected)
        elif ch == int(self._main_window.settings.get(u'Keycodes', u'KEY_CONTROL_F12', False) or -1):
            if len(self.__filelist) == 1:
                try:
                    file = self._main_window.repo_util.view(self.__filelist[0],
                        rev=self.get_selected_revision_number())
                except Exception:
                    pass
                else:
                    self._main_window.show_view_panel(file,
                        title=self.__filelist[0] + u':' + unicode(self.get_selected_revision_number()))
        # show changes in revision in workdir panel
        elif ch == ord('\n'):
            rev = self.get_selected_revision_number()
            if rev is not None:
                self.workdir_panel.set_revision_view(rev)
                self.workdir_panel.set_inactive()
        else:
            RevisionPanel.handle_keypress(self, ch, uni)
